<script setup>

import User from "@/utils/User/User.js";
import LoginDialog from "@/components/LoginDialog/LoginDialog.vue";
import {computed, onMounted, ref, watch, onUnmounted} from "vue";
import { PageStatus } from "@/views/index/const.js";
import { useRouter } from "vue-router"
import {boolean} from "mockjs/src/mock/random/basic.js";
import {AuthApi} from "@/apis/authApi.js";
import {ElMessage} from "element-plus";
import UserAvatar from "@/components/UserAvatar/UserAvatar.vue";
import FavoritesDropdown from "@/components/HeaderDropdown/FavoritesDropdown.vue";
import UserInfoDropdown from "@/components/HeaderDropdown/UserInfoDropdown.vue";


const props = defineProps({
  scrollTrans:{
    type:boolean,
    required:false,
    default:true,
  },
  searchType:{
    type:boolean,
    required:false,
    default:true,
  }

})

const router = useRouter();
const pageStatus = ref(null)
const isScrolled = ref(false)
const isLogining = computed(()=>{return pageStatus.value === PageStatus.LOGIN})
/**
 * @typedef {Object} User
 * @property {number} userid
 * @property {string} userAccount
 * @property {string} Password
 * @property {string} Permissions
 * @property {string} nickName
 * @property {string} avatarUrl
 * @property {string} gender
 * @property {Date} birthday
 * @property {number} follows_num
 * @property {number} userDynamics_num
 * @property {number} fans_num
 * @property {string} collection_list
 */
/** @type {import('vue').Ref<User>} */
const userInfo = ref({
  userid: 0,
  userAccount: '',
  Password: '',
  Permissions: '',
  nickName: '',
  avatarUrl: '',
  gender: '',
  birthday: new Date(),
  follows_num: 0,
  userDynamics_num: 0,
  fans_num: 0,
  collection_list: ''
})

const favoritesDropdownVisible = ref(false)
const userInfoDropdownVisible = ref(false);

function handleScroll() {
  if(!props.scrollTrans){
    return
  }
  isScrolled.value = window.scrollY > 100
}

onMounted(()=>{
  pageStatus.value = PageStatus.LOADING;
  window.addEventListener('scroll', handleScroll)
  if(!props.scrollTrans){
    isScrolled.value = true;
  }
  if(User.isLogin()){
    getUserInfo()
  }
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

function handleToLoginDialog(){
  console.log('handleToLoginDialog')
  pageStatus.value = PageStatus.LOGIN;
}

function handleFromLoginDialog(value){
  if(value){
    pageStatus.value = PageStatus.LOGIN;
  } else {
    pageStatus.value = PageStatus.SUCCESS;
  }

}

watch(pageStatus, (newValue) => {
  console.log('pageStatus',newValue)
})
watch(isLogining, (newValue) => {
  console.log('isLogining',newValue)
})

// 获取用户信息
const getUserInfo = async () => {
  if( User.isLogin() ){
    try {
      const res = await User.getUserInfo();
      userInfo.value = res;
    } catch (e){
      console.error(e)
      ElMessage.error('获取用户信息失败')
    }
  }
}


// 新增搜索相关的响应式变量
const searchKeyword = ref('')
const isSearchFocused = ref(false)
const searchHistory = ref(['CSGO2', 'React', 'Vue.js', '原神', '搞笑视频'])

// 处理搜索提交
function handleSearch() {
  if (!searchKeyword.value.trim()) return

  // 添加到搜索历史
  if (!searchHistory.value.includes(searchKeyword.value)) {
    searchHistory.value.unshift(searchKeyword.value)
    if (searchHistory.value.length > 6) {
      searchHistory.value.pop()
    }
  }

  // TODO: 实际搜索逻辑
  console.log('搜索关键词:', searchKeyword.value)
  router.push({
    path: '/search',
    query: { keyword: searchKeyword.value }
  })
}

// 导航函数
// 导航至用户首页
const naviToUserPage = (view)=>{
  const query = {
      view: null
  };
  if(view === 'favorites'){
    query.view = 'favorites'
  }
  router.push({
    name: 'user',
    params: {
      userid: userInfo.value.userid,
    },
    query
  })
}

// 清除搜索历史
function clearHistory() {
  searchHistory.value = []
}

// 点击历史记录
function searchHistoryItem(keyword) {
  searchKeyword.value = keyword
  handleSearch()
}

// 删除单个历史记录
function removeHistoryItem(index) {
  searchHistory.value.splice(index, 1)
}

</script>

<template>
<div class="IndexHeader" :class="{ 'is-scrolled': isScrolled }">
  <div class="IndexHeader-left">
    <div class="home-btn" @click="router.push({name:'index'})">
      <i class="iconfont icon-shouyeweixuanzhong"/>
      <span>首页</span>
    </div>
    <span>热门</span>
    <span>会员购</span>
  </div>
  <div class="IndexHeader-centerSearch" v-if="searchType">
    <div class="search-wrapper">
      <div class="search-container" :class="{ 'is-focused': isSearchFocused }">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索视频"
            @focus="isSearchFocused = true"
            @blur="isSearchFocused = false"
            @keyup.enter="handleSearch"
          >
          </el-input>
          <div class="search-btn" @click="handleSearch">
            <i class="iconfont icon-sousuo"></i>
          </div>
        </div>

<!--        &lt;!&ndash; 搜索历史下拉框 &ndash;&gt;-->
<!--        <div v-show="isSearchFocused" class="search-dropdown">-->
<!--          <div class="search-history">-->
<!--            <div class="history-header">-->
<!--              <span>搜索历史</span>-->
<!--              <span class="clear-history" @click="clearHistory">清空</span>-->
<!--            </div>-->
<!--            <div class="history-list">-->
<!--              <div-->
<!--                v-for="(item, index) in searchHistory"-->
<!--                :key="index"-->
<!--                class="history-item"-->
<!--              >-->
<!--                <div class="history-item-content" @click="searchHistoryItem(item)">-->
<!--                  <i class="iconfont icon-time"></i>-->
<!--                  <span>{{ item }}</span>-->
<!--                </div>-->
<!--                <i-->
<!--                  class="iconfont icon-close delete-btn"-->
<!--                  @click.stop="removeHistoryItem(index)"-->
<!--                ></i>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
      </div>
    </div>
  </div>
  <div class="IndexHeader-right">
    <div class="right-item">
      <div
          v-if="!User.isLogin()"
          class="header-login-entry"
          @click="handleToLoginDialog()"
      >
        <span>登录</span>
      </div>
      <div v-else class="icon-btn-box"
           @mouseenter="userInfoDropdownVisible = true"
           @mouseleave="userInfoDropdownVisible = false"
           @click="naviToUserPage"
      >
        <UserAvatar></UserAvatar>
      </div>
      <user-info-dropdown v-model="userInfoDropdownVisible"
      v-on:open-login-dialog="handleToLoginDialog()"
      ></user-info-dropdown>
    </div>
    <div class="right-item" @click="router.push({name:'dynamic'})">
      <div class="icon-btn-box">
        <i class="iconfont icon-sixin"/><span>消息</span>
      </div>
    </div>
    <div class="right-item" @click="router.push({name:'dynamic'})">
      <div class="icon-btn-box">
        <i class="iconfont icon-dongtaixuanzhong"/><span>动态</span>
      </div>
    </div>
    <div class="right-item" >
      <div class="icon-btn-box"
           @mouseenter="favoritesDropdownVisible = true"
           @mouseleave="favoritesDropdownVisible = false"
           @click="naviToUserPage('favorites')"
      >
        <i class="iconfont icon-shoucangtianchong"/><span>收藏</span>
      </div>
      <favorites-dropdown v-model="favoritesDropdownVisible"></favorites-dropdown>
    </div>
    <div class="right-item">
      <div class="icon-btn-box">
        <i class="iconfont icon-lishijilu1"/><span>历史</span>
      </div>
    </div>
    <div class="right-item" @click="router.push({name:'platform.home'})"><i class="iconfont icon-chuangzuozhongxin"/><span>创作中心</span></div>

    <div class="right-upload">
      <el-button @click="router.push({name:'platform.upload'})" ><i class="iconfont icon-shoucangjia"></i>  <span>投稿</span> </el-button>
    </div>

  </div>
</div>

  <LoginDialog v-model="isLogining" @update:pageStatus="handleFromLoginDialog"></LoginDialog>
</template>

<style scoped lang="less">
.iconfont{
  max-height: 25px;
  font-size: 20px;
  color: white;
  transition: color 0.3s ease;
}
.IndexHeader{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1002;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  max-width: 2560px;
  width: 100%;
  height: 64px;
  transition: all 0.3s ease;

  background-color: transparent;

  span{
    font-family: PingFang SC, HarmonyOS_Regular, Helvetica Neue, Microsoft YaHei, sans-serif !important;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    color: white;
    transition: color 0.3s ease;
  }

  &-left{
    flex: 1 0 200px;
    display: flex;
    align-items: center;
    margin-right: 30px;
    .iconfont{
      font-size: 18px;
      margin-right: 3px;
      transform:translateY(-2px);
    }

    span{
      font-family: PingFang SC, HarmonyOS_Regular, Helvetica Neue, Microsoft YaHei, sans-serif !important;
      height: 64px;
      line-height: 64px;
      color: #fff;
      font-size: 15px;
      font-weight: 500;
      cursor: pointer;
      margin-right: 10px;
      transition: color 0.3s ease;
    }
  }

  &-centerSearch{
    position: relative;
    flex: 1;
    max-width: 500px;
    min-width: 181px;
    margin: 0 20px;

    .search-wrapper {
      background-color: var(--search-background, rgba(255, 255, 255, 0.8));
      border-radius: 8px;
      padding: 4px;
      transition: all 0.3s;

      .search-container {
        position: relative;

        &.is-focused {
          .search-box {
            border-radius: 4px 4px 0 0;

            .el-input__wrapper {
              border-radius: 4px 4px 0 0;
            }

            .search-btn {
              border-radius: 0 4px 0 0;
            }
          }

          .search-dropdown {
            visibility: visible;
            opacity: 1;
          }
        }
      }

      .search-box {
        display: flex;
        align-items: center;
        height: 32px;
        background-color: #f1f2f3;
        border-radius: 4px;
        transition: all 0.3s;

        :deep(.el-input) {
          width: 100%;

          .el-input__wrapper {
            background: transparent;
            box-shadow: none !important;
            padding-right: 40px;
            border-radius: 4px;
            height: 32px;
          }

          .el-input__inner {
            height: 32px;
            color: #18191c;
            font-size: 14px;

            &::placeholder {
              color: #9499a0;
            }
          }

          .el-input__prefix {
            .iconfont {
              font-size: 16px;
              color: #9499a0;
            }
          }
        }

        .search-btn {
          position: absolute;
          right: 0;
          width: 40px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          border-radius: 0 4px 4px 0;
          transition: all 0.3s;
          user-select: none;

          &:hover {
            background: var(--search-button-hover, #00aeec);
            .iconfont {
              color: #fff;
            }
          }

          .iconfont {
            font-size: 16px;
            color: #9499a0;
            transition: color 0.3s;
          }
        }
      }

      .search-dropdown {
        position: absolute;
        top: 100%;
        left: -4px;  // 对齐外层padding
        right: -4px; // 对齐外层padding
        background: #fff;
        border-radius: 0 0 8px 8px;
        visibility: hidden;
        opacity: 0;
        transition: all 0.2s;
        z-index: 1000;
        margin-top: -1px; // 消除边框间隙
      }
    }
  }

  &-right{
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-left:5%;
    .right-item{
      position: relative;
      flex: 1;
      margin: 0 3px;
      min-width: 60px;
      display: inline-flex;
      flex-direction: column;
      text-align: center;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;


      .icon-btn-box{
        transition: transform 0.1s ease;
      }
      .icon-btn-box:hover{
          transform: scale(110%);
      }
      .header-login-entry{
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #00AEEC;
        text-align: center;
        letter-spacing: 0;
        font-size: 14px;
        line-height: 36px;
        span{
          color: #fff !important;
        }
      }
      .header-avatar{
        width: 36px;
        height: 36px;
        border-radius: 50%;
        img{
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }

    }

    .right-upload{
      color: white !important;
      .el-button{
        width: 90px;
        height: 34px;
        background: #fb7299;
        border-color: #fb7299;
        border-radius: 8px;
        transition: all 0.3s ease;
        .iconfont{
          margin-right: 4px;
        }

        &:hover{
          filter: brightness(110%);
        }
      }
    }
  }

  &.is-scrolled {
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);

    .iconfont {
      color: #18191c;
    }

    span {
      color: #61666d;
    }

    .IndexHeader-right {
      .right-upload {
        span {
          color: white !important;
          font-size: 13px;
          font-weight: 600;
        }
        .iconfont {
          color: white !important;
        }
        .el-button {
          background: #fc6b9c;
          border-color: #fc6b9c;

          &:hover {
            background: #ff85ad;
            border-color: #ff85ad;
          }
        }
      }

      .right-item {
        color: #18191c;

        .header-login-entry {
          color: #fff;
        }
      }
    }

    .IndexHeader-left {
      span {
        color: #18191c;
      }
    }

    .IndexHeader-centerSearch {
      .search-wrapper {
        background-color: #fff;

        .search-box {
          background-color: #f1f2f3;

          &:hover {
            background-color: #e3e5e7;
          }
        }
      }
    }
  }
}
</style>
